#include "TwoProgressTableWidget.h"
#include <QHeaderView>
#include <QInputDialog>
#include <QLineEdit>
#include <QFormLayout>
#include <QDialogButtonBox>
#include <QContextMenuEvent>

TwoProgressTableWidget::TwoProgressTableWidget(QWidget *parent) : QTableWidget(parent) {
    // 初始化表格
    setColumnCount(0); // 初始列数为 0
    setRowCount(0);    // 初始行数为 0
    setSelectionBehavior(QAbstractItemView::SelectRows); // 选中整行
    setSelectionMode(QAbstractItemView::SingleSelection); // 单选模式
    horizontalHeader()->setStretchLastSection(true); // 最后一列填充剩余空间
    //表头渐变色
    horizontalHeader()->setStyleSheet(
        "QHeaderView::section {"
        "    background-color: qlineargradient(x1:0, y1:0, x2:0, y2:1, stop:0 #CCFFCC, stop:1 #66CC66);" // 默认背景色
        "    color: white;"              // 文字颜色
        "    padding: 4px;"              // 内边距
        "    border: 1px solid #66CC66;" // 边框
        "}"
        "QHeaderView::section:checked {"
        "background-color: qlineargradient(x1:0, y1:0, x2:0, y2:1, stop:0 #CCFFCC, stop:1 #66CC66);" // 默认背景色
        "}"
        );
    // horizontalHeader()->setStyleSheet("QHeaderView::section { background-color: qlineargradient(x1:0, y1:0, x2:0, y2:1, stop:0 #CCFFCC, stop:1 #66CC66); }");
    horizontalHeader()->setMinimumHeight(30);
    horizontalHeader()->setSectionsClickable(true);
}

// 动态添加列
void TwoProgressTableWidget::addColumn(const QString& columnName, const QString& columnType, const QVariant& defaultValue) {
    int col = columnCount();
    setColumnCount(col + 1);
    setHorizontalHeaderItem(col, new QTableWidgetItem(columnName));

    ColumnInfo colInfo;
    colInfo.type = columnType;
    colInfo.defaultValue = defaultValue;
    columnInfos.append(colInfo);
}

// 动态设置列属性
void TwoProgressTableWidget::setColumnProperty(int column, const QString& propertyName, const QVariant& value) {
    if (column >= 0 && column < columnInfos.size()) {
        columnInfos[column].properties[propertyName] = value;
    }
}

// 添加行
void TwoProgressTableWidget::addRow(const QMap<QString, QVariant>& rowData) {
    int row = rowCount();
    setRowCount(row + 1);
    fillRow(row, rowData);
}
// 添加多行数据
void TwoProgressTableWidget::addRows(const QList<QMap<QString, QVariant>>& data) {
    if (data.isEmpty()) return; // 如果数据为空，直接返回

    int currentRowCount = rowCount(); // 当前行数
    setRowCount(currentRowCount + data.size()); // 扩展行数

    // 遍历数据并填充每一行
    for (int i = 0; i < data.size(); ++i) {
        fillRow(currentRowCount + i, data[i]);
    }
}
// 删除行
void TwoProgressTableWidget::removeRow(int row) {
    if (row >= 0 && row < rowCount()) {
        QTableWidget::removeRow(row);
    }
}

// 更新行
void TwoProgressTableWidget::updateRow(int row, const QMap<QString, QVariant>& rowData) {
    if (row >= 0 && row < rowCount()) {
        fillRow(row, rowData);
    }
}

// 查询行
QMap<QString, QVariant> TwoProgressTableWidget::queryRow(int row) const {
    QMap<QString, QVariant> rowData;
    for (int col = 0; col < columnCount(); ++col) {
        QTableWidgetItem* item = this->item(row, col);
        if (item) {
            rowData[columnInfos[col].type] = item->text();
        }
    }
    return rowData;
}

// 刷新表格
void TwoProgressTableWidget::refresh() {
    clearContents();
    setRowCount(0);
}

// 根据数据来源初始化表格
void TwoProgressTableWidget::initFromData(const QList<QMap<QString, QVariant>>& data) {
    refresh();
    for (const auto& rowData : data) {
        addRow(rowData);
    }
}

// 计算某列的最大值
QVariant TwoProgressTableWidget::getColumnMax(int column) const {
    if (column < 0 || column >= columnCount()) return QVariant();

    QVariant maxValue;
    for (int row = 0; row < rowCount(); ++row) {
        QTableWidgetItem* item = this->item(row, column);
        if (item) {
            QVariant value = item->data(Qt::DisplayRole);
            if (value.isValid() && value.canConvert<double>()) {
                double currentValue = value.toDouble();
                if (!maxValue.isValid() || currentValue > maxValue.toDouble()) {
                    maxValue = currentValue;
                }
            }
        }
    }
    return maxValue;
}

// 计算某列的最小值
QVariant TwoProgressTableWidget::getColumnMin(int column) const {
    if (column < 0 || column >= columnCount()) return QVariant();

    QVariant minValue;
    for (int row = 0; row < rowCount(); ++row) {
        QTableWidgetItem* item = this->item(row, column);
        if (item) {
            QVariant value = item->data(Qt::DisplayRole);
            if (value.isValid() && value.canConvert<double>()) {
                double currentValue = value.toDouble();
                if (!minValue.isValid() || currentValue < minValue.toDouble()) {
                    minValue = currentValue;
                }
            }
        }
    }
    return minValue;
}

// 根据指定列排序
void TwoProgressTableWidget::sortByColumn(int column, Qt::SortOrder order) {
    if (column >= 0 && column < columnCount()) {
        sortItems(column, order);
    }
}

// 重写右键点击事件
void TwoProgressTableWidget::contextMenuEvent(QContextMenuEvent *event) {
    QMenu menu(this);
    QAction* addAction = menu.addAction("Add Data");
    QAction* editAction = menu.addAction("Edit Data");
    QAction* deleteAction = menu.addAction("Delete Data");
    QAction* exportAction = menu.addAction("Export Data");

    connect(addAction, &QAction::triggered, this, &TwoProgressTableWidget::onAddData);
    connect(editAction, &QAction::triggered, this, &TwoProgressTableWidget::onEditData);
    connect(deleteAction, &QAction::triggered, this, &TwoProgressTableWidget::onDeleteData);
    connect(exportAction, &QAction::triggered, this, &TwoProgressTableWidget::onExportData);

    menu.exec(event->globalPos());
}

// 填充一行数据
void TwoProgressTableWidget::fillRow(int row, const QMap<QString, QVariant>& rowData) {
    for (int column = 0; column < columnCount(); ++column) {
        QString columnName = horizontalHeaderItem(column)->text();
        QVariant value = rowData.contains(columnName) ? rowData[columnName] : columnInfos[column].defaultValue;

        if (columnInfos[column].type == "button") {
            // 按钮列
            QPushButton* button = new QPushButton(value.toString(), this);
            button->setCheckable(true);
            button->setStyleSheet("QPushButton:checked { background-color: green; }");
            connect(button, &QPushButton::toggled, this, [button](bool checked) {
                button->setText(checked ? "启用" : "未启用");
            });
            setCellWidget(row, column, button);
        } else if (columnInfos[column].type == "color") {
            // 颜色按钮列
            QPushButton* colorButton = new QPushButton("", this);
            QColor color = value.value<QColor>();
            // 使用样式表设置按钮背景颜色
            colorButton->setStyleSheet(QString("background-color: %1;").arg(color.name()));
            connect(colorButton, &QPushButton::clicked, this, [this, row, column]() {
                // 弹出颜色选择对话框
                QColor color = QColorDialog::getColor(Qt::white, this, "选择颜色");
                if (color.isValid()) {
                    // 更新按钮的背景颜色
                    QPushButton* button = qobject_cast<QPushButton*>(cellWidget(row, column));
                    if (button) {
                        button->setStyleSheet(QString("background-color: %1;").arg(color.name()));
                    }
                    // 如果需要将颜色存储到表格项中
                    QTableWidgetItem* item = this->item(row, column);
                    if (item) {
                        item->setBackground(color);
                    }
                }
            });
         setCellWidget(row, column, colorButton);
        } else if (columnInfos[column].type == "progress") {
            // 进度条列
            CustomProgressWidget* progressWidget = new CustomProgressWidget(this);
            progressWidget->setRange(-value.toMap()["value"].toInt(), value.toMap()["value"].toInt());
            progressWidget->setMinMax(value.toMap()["min"].toInt(),value.toMap()["max"].toInt());
            progressWidget->setUnit(value.toMap()["unit"].toString());
            progressWidget->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed);
            setCellWidget(row, column, progressWidget);
        } else {
            // 文本列
            setItem(row, column, new QTableWidgetItem(value.toString()));
        }
    }
}

// 弹出输入对话框
QMap<QString, QVariant> TwoProgressTableWidget::showInputDialog(const QMap<QString, QVariant>& initialData) {
    QMap<QString, QVariant> result;
    QDialog dialog(this);
    QFormLayout form(&dialog);
    for (const ColumnInfo& colInfo : columnInfos) {
        QLineEdit* edit = new QLineEdit(&dialog);
        edit->setText(initialData.value(colInfo.type, colInfo.defaultValue).toString());
        form.addRow(colInfo.type, edit);
        result[colInfo.type] = edit->text();
    }
    QDialogButtonBox buttonBox(QDialogButtonBox::Ok | QDialogButtonBox::Cancel, Qt::Horizontal, &dialog);
    form.addRow(&buttonBox);
    connect(&buttonBox, &QDialogButtonBox::accepted, &dialog, &QDialog::accept);
    connect(&buttonBox, &QDialogButtonBox::rejected, &dialog, &QDialog::reject);
    if (dialog.exec() == QDialog::Accepted) {
        return result;
    }
    return {};
}

// 添加数据
void TwoProgressTableWidget::onAddData() {
    QMap<QString, QVariant> newData = showInputDialog();
    if (!newData.isEmpty()) {
        addRow(newData);
    }
}

// 编辑数据
void TwoProgressTableWidget::onEditData() {
    int row = currentRow();
    if (row >= 0) {
        QMap<QString, QVariant> rowData = queryRow(row);
        QMap<QString, QVariant> newData = showInputDialog(rowData);
        if (!newData.isEmpty()) {
            updateRow(row, newData);
        }
    }
}

// 删除数据
void TwoProgressTableWidget::onDeleteData() {
    int row = currentRow();
    if (row >= 0) {
        removeRow(row);
    }
}

// 导出数据
void TwoProgressTableWidget::onExportData() {
    QString fileName = QFileDialog::getSaveFileName(this, "Export Data", "", "CSV Files (*.csv)");
    if (!fileName.isEmpty()) {
        QFile file(fileName);
        if (file.open(QIODevice::WriteOnly | QIODevice::Text)) {
            QTextStream stream(&file);
            // 导出表头
            for (int col = 0; col < columnCount(); ++col) {
                stream << horizontalHeaderItem(col)->text();
                if (col < columnCount() - 1) stream << ",";
            }
            stream << "\n";
            // 导出数据
            for (int row = 0; row < rowCount(); ++row) {
                for (int col = 0; col < columnCount(); ++col) {
                    QTableWidgetItem* item = this->item(row, col);
                    if (item) {
                        stream << item->text();
                    }
                    if (col < columnCount() - 1) stream << ",";
                }
                stream << "\n";
            }
            file.close();
        }
    }
}

/**
 * @brief TwoProgressTableWidget::setRows
 * @param vecDeviceChannel
 * 金雪松添加的
 */
void TwoProgressTableWidget::setRows(QVector<DeviceChannel*>& vecDeviceChannel){
    m_vecDeviceChannel = &vecDeviceChannel;
    if (vecDeviceChannel.isEmpty()) return; // 如果数据为空，直接返回

    int currentRowCount = rowCount(); // 当前行数
    setRowCount(currentRowCount + vecDeviceChannel.size()); // 扩展行数

    // 遍历数据并填充每一行
    for (int i = 0; i < vecDeviceChannel.size(); ++i) {
        fillRow(i,vecDeviceChannel[i]);
    }
}

/**
 * @brief TwoProgressTableWidget::fillRow
 * @param row
 * @param rowData
 *  * 金雪松添加的
 */
void TwoProgressTableWidget::fillRow(int row,const DeviceChannel* rowData){
    //int r = 0,c = 0;
    for (int col = 0; col < columnCount(); ++col) {
        QString columnName = horizontalHeaderItem(col)->text();
        //QVariant value = rowData.contains(columnName) ? rowData[columnName] : columnInfos[col].defaultValue;

        if (columnInfos[col].type == "button") {
            // 按钮列
            QPushButton* button = new QPushButton(rowData->m_bEnabled ? "启用" : "未启用", this);
            button->setCheckable(true);
            button->setStyleSheet("QPushButton:checked { background-color: green; }");
            connect(button, &QPushButton::toggled, this, [button](bool checked) {
                button->setText(checked ? "启用" : "未启用");
            });
            setCellWidget(row, col, button);
        }else if (columnInfos[col].type == "color") {
            // 检查 rowData 是否为空
            if (rowData == nullptr) {
                qWarning() << "rowData is null!";
                return;
            }

            // 检查列索引是否有效
            if (col < 0 || col >= columnInfos.size()) {
                qWarning() << "Column index out of range!";
                return;
            }

            // 检查行索引是否有效
            if (row < 0 || row >= m_vecDeviceChannel->size()) {
                qWarning() << "Row index out of range!";
                return;
            }

            // 创建颜色按钮
            QPushButton* colorButton = new QPushButton("", this);
            QColor color = rowData->m_cColor;

            // 使用样式表设置按钮背景颜色
            colorButton->setStyleSheet(QString("background-color: %1; border: none;").arg(color.name()));

            // 连接按钮点击信号
            connect(colorButton, &QPushButton::clicked, this, [=] {
                qDebug() << "Button clicked for row:" << row << "col:" << col;

                // 打开颜色选择对话框
                qDebug() << "Opening color dialog...";
                QColor newColor = QColorDialog::getColor(Qt::white, this, "选择颜色");
                qDebug() << "Color selected:" << newColor;

                if (newColor.isValid()) {
                    // 获取或创建 QTableWidgetItem
                    QTableWidgetItem* item = TwoProgressTableWidget::item(row, 1);
                    if (item == nullptr) {
                        qDebug() << "Creating new QTableWidgetItem for row:" << row << "col: 1";
                        item = new QTableWidgetItem();
                        TwoProgressTableWidget::setItem(row, 1, item);
                    }
                    qDebug() << "Item set for row:" << row << "col: 1";

                    // 设置背景颜色
                    item->setData(Qt::BackgroundRole, newColor);
                    qDebug() << "Background color set for row:" << row << "col: 1";

                    // 更新 m_vecDeviceChannel 中的颜色
                    if (row < 0 || row >= m_vecDeviceChannel->size()) {
                        qWarning() << "Row index out of range for m_vecDeviceChannel!";
                        return;
                    }
                    qDebug() << "Updating color for row:" << row;
                    m_vecDeviceChannel->at(row)->m_cColor = newColor;
                    // QModelIndex index = index(row,1); // 获取第一行第一列的索引
                    // dataChanged(index, index); // 通知视图数据已改变
                }
            });

            // 清理旧的 cell widget
            QWidget* oldWidget = cellWidget(row, col);
            if (oldWidget) {
                oldWidget->deleteLater();
            }

            // 设置新的 cell widget
            setCellWidget(row, col, colorButton);
        }else if (columnInfos[col].type == "progress") {
            // 进度条列
            CustomProgressWidget* progressWidget = new CustomProgressWidget(this);
            progressWidget->setRange(rowData->m_dlbMeasureRangeMin,rowData->m_dlbMeasureRangeMax);
            progressWidget->setUnit(rowData->m_strUnit);
            progressWidget->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed);
            setCellWidget(row, col, progressWidget);

            progressWidget->setMinMax(rowData->m_dblMinimunValue,rowData->m_dblMaximunValue);
            m_vecProgressWidgets.append(progressWidget);
        } else {
            // 文本列
            if(columnName == "名称"){
                setItem(row, col, new QTableWidgetItem(rowData->m_strChannelName));
            }else if(columnName == "放大器名称"){
                setItem(row, col, new QTableWidgetItem(rowData->m_strAmplifierName));
            }else if(columnName == "量程"){
                setItem(row, col, new QTableWidgetItem(QString::number(rowData->m_dlbMeasureRangeMax - rowData->m_dlbMeasureRangeMin)));
            }else if(columnName == "最小值"){
                setItem(row, col, new QTableWidgetItem(QString::number(rowData->m_dlbMeasureRangeMin)));
            }else if(columnName == "最大值"){
                setItem(row, col, new QTableWidgetItem(QString::number(rowData->m_dlbMeasureRangeMax)));
            }else{

            }
        }
    }
}

void TwoProgressTableWidget::updateRowValue(int row,double value){
    m_vecProgressWidgets[row]->setValue(value);
}
